package com.daxia.bumall.web.controller;

import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.daxia.bumall.common.MyJSONObject;
import com.daxia.bumall.common.SeedStatus;
import com.daxia.bumall.common.UserType;
import com.daxia.bumall.dto.CityDTO;
import com.daxia.bumall.dto.DistrictDTO;
import com.daxia.bumall.dto.ProvinceDTO;
import com.daxia.bumall.dto.SeedDTO;
import com.daxia.bumall.dto.UserDTO;
import com.daxia.bumall.model.City;
import com.daxia.bumall.model.Province;
import com.daxia.bumall.model.User;

@Controller
@RequestMapping("seed/")
public class SeedController extends BaseController {
 
	private static final Logger logger = Logger.getLogger(SeedController.class);
	
	@RequestMapping("index")
	public String index(Map<String, Object> map) {
		
		List<CityDTO> citys = cityService.getCitysFromUserType(UserType.City.getValue());
		List<ProvinceDTO> provinces = provinceService.findAll();
		
		CityDTO cityQuery = new CityDTO();
		Province province = new Province();
		province.setId(3L);
		cityQuery.setProvince(province );
		List<CityDTO> cts = cityService.find(cityQuery, null);
		
		DistrictDTO districtQuery = new DistrictDTO();
		City city = new City();
		city.setId(1L);
		districtQuery.setCity(city );
		List<DistrictDTO> districts = districtService.find(districtQuery, null);
		map.put("citys", citys);
		map.put("provinces", provinces);
		map.put("cts", cts);
		map.put("districts", districts);
		return "seed/seed_index";
	}
	
	@RequestMapping("agreement")
	public String agreement() {
		
		return "seed/seed_agreement";
	}
	
	@RequestMapping(value = "save", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String save(UserDTO userDTO, SeedDTO seedDTO) throws Exception {
		logger.info(userDTO);
		MyJSONObject  data = new MyJSONObject();
		data.put("seccuess", true);
		data.put("message", "报名成功！登录账号为手机号，默认密码为123456，请及时修改密码!");
		
		UserDTO exist = userService.findByMobile(userDTO.getMobile());
		if (exist != null) {
			data.put("seccuess", true);
			data.put("message", "您已经报名成功！");
			return toJson(data);
		}
		
		userDTO.setUsername(userDTO.getMobile());
		userDTO.setSeedUser(true);
		userDTO.setType(UserType.Seed.getValue());
		userDTO.setSeedStatus(SeedStatus.nodetermined.getValue());
		userDTO.setCity(seedDTO.getCity());
		userDTO.setProvince(seedDTO.getProvince());
		userDTO.setDistrict(seedDTO.getDistrict());
		userDTO.setPassword(passwordEncoder.encodePassword("123456", userDTO.getUsername()));
		
		Long userId = userService.create(userDTO);
		
		User user = new User();
		user.setId(userId);
		seedDTO.setUser(user);
		
		seedService.create(seedDTO);
		return toJson(data);
	}
	
}
